package com.gitee.hifong45.config;

import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.text.AntPathMatcher;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
@WebFilter(filterName = "commonFilter",urlPatterns = "/*")
public class BaseFilter implements Filter {
    @Resource
    WebApplicationContext applicationContext;

    public List<String> urlNeedFilter = ListUtil.of("/**swagger**/**"); //, "/**/swagger**/**");
    
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        boolean need = needFilter(request.getRequestURI());
        if(need) {
            log.debug("过滤 {}", uri);
            servletRequest.getRequestDispatcher("/failed").forward(servletRequest,servletResponse); // 返回
        } else {
            filterChain.doFilter(servletRequest,servletResponse); // 继续
        }
    }

    private boolean needFilter(String url) {
		return urlNeedFilter.stream().anyMatch(pattern -> antPathMatcher.match(pattern, url));
	}

    public static void main(String[] args) {
        BaseFilter filter = new BaseFilter();
        Console.log("{}", filter.urlNeedFilter);
        List<String> urls = ListUtil.of("/swagger-ui.html", "/swagger-ui/index.html", "/swagger-ui/swagger-ui.css", "/v3/api-docs/swagger-config", "/v3/api-docs");
        for(String url : urls) {
            Console.log("{}= {}", filter.needFilter(url), url);
        }
        
    }

}
